import { mapCompositionCoord } from './mapCompositionCoord.util'
import { validateComposition } from './validateCompositionData.util'

export function mergeCompositionSvg(composition) {
  if (!validateComposition(composition)) { return; }
  // if (composition.structure === 'SINGLE') { return composition.components.SINGLE.svgCode; }

  let symbolDefs = '';
  let useTags = '';

  const coordinates = mapCompositionCoord(composition);
  const { components } = composition;
  for (const key in components) {
    const { graphicId, svgCode } = components[key];
    const symbolId = `graphic-${graphicId}`;
    const viewBox = matchViewBox(svgCode);

    const svgContent = svgCode.trim().replace(/<svg(S*?)[^>]*>/, '').replace(/<\/svg>$/, '');    // Convert each SVG graphic to a symbol
    symbolDefs += `<symbol id="${symbolId}" viewBox="${viewBox}">${svgContent}</symbol>`;

    // Calculate position based on the "based" property
    const { x, y, width, height } = coordinates[key];
    useTags += `<use xlink:href="#${symbolId}" x="${x}" y="${y}" width="${width}" height="${height}" />`;

  }

  const viewBox = calcViewBox(coordinates)
  // Wrap the use tags in an svg tag
  const mergedSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox=${viewBox}>${symbolDefs}${useTags}</svg>`;
  return mergedSVG;

}
function calcViewBox(coordinates) {
  let boxWidth = 0; let boxHeight = 0;
  for (const key in coordinates) {
    const { x, y, width, height } = coordinates[key];
    if (boxWidth < x + width) { boxWidth = x + width }
    if (boxHeight < y + height) { boxHeight = y + height }
  }
  const viewBox = `"0 0 ${boxWidth} ${boxHeight}"`
  return viewBox
}

const structue = ` 
<svg>
    <symbol id="sym01" viewBox="0 0 150 110">
      <circle cx="50" cy="50" r="40" stroke-width="8" stroke="red" fill="red" />
    </symbol>

    <use xlink:href="#sym01" x="0" y="0" width="100" height="50" />
    <use xlink:href="#sym01" x="0" y="50" width="75" height="38" />
</svg>
`

function convertToSymbol(svgCode, id) {
  const symbolSVG = svgCode.replace(/^<svg/, '<symbol').replace(/<\/svg>$/, '</symbol>');
  return `<symbol id="symbol" viewBox="0 0 150 110">${svgCode}</symbol>`;
}

function matchViewBox(svgCode = '') {
  const viewBoxMatch = svgCode.match(/viewBox="([^"]+)"/);
  const match = svgCode.match(/viewBox="([^"]+)"/);
  return match ? match[1] : null;
}


// Example usage
export const graphics = {
  "LEFT": {
    "graphicId": 1,
    "size": 1,
    "based": "height",
    "margin": "0 1 0 0",
    "name": "audi logo",
    "svgCode": `<svg viewBox="0 0 100 100"><circle cx='50' cy='50' r='40' fill='red' /></svg>`,
  },
  "RIGHT": {
    "graphicId": 2,
    "based": "height",
    "size": 1,
    "margin": "0 0 0 1",
    "name": "yiqi logo",
    "svgCode": `<svg viewBox="10 10 70 70" ><rect x='10' y='10' width='60' height='60' fill='blue' /></svg>`,
  }
};

// const mergedSVGCode = mergeSVGGraphics(graphics);
// console.log(mergedSVGCode);
